//
//  CZComposeViewController.swift
//  WeiBo
//
//  Created by Apple on 16/9/7.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

//  撰写控制器
class CZComposeViewController: UIViewController {

    // MARK:    - 懒加载控件
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: #selector(sendButtonAction), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    
    //  自定义标题
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15)
        //  文本居中
        label.textAlignment = .center
        if let name = CZUserAccountViewModel.sharedUserAccount.userAccount?.name {
            //  使用富文本的方式显示
            let title = "发微博\n\(name)"
            //  创建富文本对象
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
            
            let nameRange = (title as NSString).range(of: name)
            //  设置字体大小
            attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: nameRange)
            //  设置文字颜色
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: nameRange)
            
            //  设置富文本
            label.attributedText = attributedStr
            
            
        } else {
            label.text = "发微博"
        }
        
        //  多行显示
        label.numberOfLines = 0
        //  设置大小
        label.sizeToFit()
        return label
    }()
    
    //  撰写文本框
    fileprivate lazy var textView: CZComposeTextView = {
        let view = CZComposeTextView()
        view.placeHolder = "听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~~听说下雨天音乐跟辣条更配哟~听说下雨天音乐跟辣条更配哟~"
        view.font = UIFont.systemFont(ofSize: 13)
        //  设置文字颜色
        view.textColor = UIColor.darkGray
        //  设置垂直方向滚动
        view.alwaysBounceVertical = true
        //  设置代理
        view.delegate = self
        //  不纠错
        view.autocorrectionType = UITextAutocorrectionType.no
        return view
    
    }()
    
    
    //  撰写按钮的toolBar
    fileprivate lazy var toolBar: CZComposeToolBar = {
        //  原来这样写不行，需要传入一个frame，swift 3.0可以
        let view = CZComposeToolBar()
        view.backgroundColor = UIColor.red
        return view
    }()
    
    //  配图
    fileprivate lazy var pictureView: CZComposePictureView = {
        let view = CZComposePictureView()
        view.backgroundColor = self.textView.backgroundColor
        return view
    }()
    
    //  表情键盘
    fileprivate lazy var emoticonKeyBoard: CZEmoticonKeyBoard = {
        let view = CZEmoticonKeyBoard()
        //  设置大小
        view.size = CGSize(width: self.textView.width, height: EmoticonKeyBoardHeight)
        return view
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    private func setupUI() {
        
        view.backgroundColor = UIColor.white
        //  监听键盘改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //  监听点击表情按钮的通知名
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonAction(noti:)), name: NSNotification.Name(DidSelectedEmoticonNotification), object: nil)
        setupNavUI()
        //  添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        
        //  配图添加到textview上
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) in
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.top.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
    
        
        //  设置toolbar点击按钮的闭包, 使用self需要注意循环引用
        toolBar.didSelectedToolBarButtonClosure = { [weak self] (type) in
        
            switch type {
            case .picture:
                print("图片")
                self?.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emotion:
                print("表情")
                self?.didSelectedEmoticon()
            case .add:
                print("加号")
                
            }
            
        }
        
        //  设置选择图片浏览器的闭包
        pictureView.addImageClosure = { [weak self] in
            self?.didSelectedPicture()
        }
        
        
    }
    
    private func setupNavUI() {
        
        
        //  自定义标题
        navigationItem.titleView = titleLabel
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(leftAction))
        
        //  右边发微博按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        //  默认右边的按钮不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    
    // MARK:    --键盘frame改变的通知
    @objc private func keyBoardFrameChange(noti: Notification) {
        //  键盘的frame
        let keyBoardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        //  动画时长
        let animationDuration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        //  更新约束
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - ScreenHeight)
        }
        //  执行约束动画
        UIView.animate(withDuration: animationDuration) { 
            self.view.layoutIfNeeded()
        }
        
        
        
        
        
    }
    
    // MARK:    --监听表情按钮的点击
    @objc private func didSelectedEmoticonAction(noti: Notification) {
        let emoticon = noti.object as! CZEmoticon
        
        //  插入富文本
        textView.insertEmoticon(emoticon: emoticon)
        
//        if emoticon.type == "0" {
//            //  图片转成富文本
//            
//            //  记录上次的富文本
//            let lastAttributedStr = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            //  1. 创建image对象(通过图片路径创建对象)
//            let image = UIImage(named: emoticon.path!)
//            //  2. 通过image对象创建文本附件
//            let attachment = NSTextAttachment()
//            attachment.image = image
//            //  设置大小
//            let fontHeight = textView.font!.lineHeight
//            attachment.bounds = CGRect(x: 0, y: -3, width: fontHeight, height: fontHeight)
//            //  3. 通过文本附件创建富文本
//            let attributedStr = NSAttributedString(attachment: attachment)
//            
//            //  获取选中的范围
//            var selectedRange = textView.selectedRange
//            
//            //  替换选中的范围
//            lastAttributedStr.replaceCharacters(in: selectedRange, with: attributedStr)
//            
//            //  追加点击的富文本
//            //lastAttributedStr.append(attributedStr)
//            
//            //  设置富文本的字体大小
//            lastAttributedStr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, lastAttributedStr.length))
//            //  4. 设置富文本
//            textView.attributedText = lastAttributedStr
//            
//            //  点击一个表情让其的选中开始位置往后加1
//            selectedRange.location += 1; selectedRange.length = 0
//            
//            //  设置选中的范围
//            textView.selectedRange = selectedRange
//            
//            
//            
//            
//            
//            
//        } else {
//            //  插入文字
//            let emoji = (emoticon.code! as NSString).emoji()
//            textView.insertText(emoji!)
//        }
    }
    
    // MARK:    --点击事件
    @objc private func leftAction() {
        //  让其失去第一响应者
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    
    }
    // MARK:    --发送微博
    @objc private func sendButtonAction() {
        
        
        //  访问令牌
        let accessToken = CZUserAccountViewModel.sharedUserAccount.accessToken!
        //  微博内容
        let status = textView.emoticonString //textView.text!
        //  加载提示
        SVProgressHUD.show()
        
        
        
        if pictureView.images.count > 0 {
            
            let image = pictureView.images.first!
            CZNetworkTools.sharedTools.upload(accessToken: accessToken, status: status, image: image, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                
                
            })
            
        } else {
            CZNetworkTools.sharedTools.update(accessToken: accessToken, status: status) { (reponse, error) in
                
                if error != nil {
                    SVProgressHUD.showError(withStatus: "网络请求异常")
                    print(error)
                    return
                }
                
                //  代码执行到此，发送成功
                SVProgressHUD.showSuccess(withStatus: "发送成功!")
                
            }
        }
        
        
    }
    
}

// MARK:    --点击toolbar执行的函数
extension CZComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //  处理点击表情按钮的逻辑
    func didSelectedEmoticon() {
        
        if textView.inputView == nil {
            //  设置为表情键盘
            textView.inputView = emoticonKeyBoard
            //  切换表情键盘icon
            toolBar.showEmoticonIcon(isEmoticon: true)
        } else {
            //  设置为系统键盘
            textView.inputView = nil
            toolBar.showEmoticonIcon(isEmoticon: false)
        }
        if !textView.isFirstResponder {
            //  设置第一响应者
            textView.becomeFirstResponder()            
        }
        
        //  重新加载inputview
        textView.reloadInputViews()
        
        
    }
    
    //  处理点击图片的逻辑
    func didSelectedPicture() {
        
        let pictureVc = UIImagePickerController()
        //  判断是否支持摄像头
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            pictureVc.sourceType = .camera
        } else {
            //  相册
            pictureVc.sourceType = .photoLibrary
        }
        
        //  判断是否支持前后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            //  
            print("支持前置摄像头")
        } else if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            print("支持后置摄像头")
        } else {
            print("不支持摄像头")
        }
        
        //  设置编辑
//        pictureVc.allowsEditing = true
        
        pictureVc.delegate = self
        
        //  模态图片浏览控制器
        present(pictureVc, animated: true, completion: nil)
        
        
        
    }
    
    //  点击了那张图片，重写方法，那么dismis操作需要自己去做
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //  获取选中的图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //  压缩后的图片,  等比压缩图片
        let scaleImage = self.scaleImage(scaleWidth: 200, image: image)
    
        //  添加图片
        pictureView.addImage(image: scaleImage)
        
        picker.dismiss(animated: true, completion: nil)
        
    }
    
    //  取消
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
       picker.dismiss(animated: true, completion: nil)
    }
    
    
    //  等比压缩图片
    func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        
        //  根据压缩后的宽度，计算压缩后的高度
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        //  压缩后的大小
        let size = CGSize(width: scaleWidth, height: scaleHeight)
        UIGraphicsBeginImageContext(size)
        //  绘制到指定区域
        image.draw(in: CGRect(origin: CGPoint.zero, size: size))
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        return scaleImage!
        
    }
    
    
}

// MARK:    --UITextViewDelegate
extension CZComposeViewController: UITextViewDelegate {
    //  文字改变的代理方法
    func textViewDidChange(_ textView: UITextView) {
        //  让其右边的按钮启用，假如有文本内容
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        
    }
    //  拖动textview的时候让其隐藏键盘
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}





